package ULHT.LIG2N1.RC.CLIENT;

import java.io.IOException;
import java.net.*;

public class Client {

    private static int TCPport = 6501, maxConnections = 0, UDPport = 9031, UDPmulticastPort = 9013;
    private static String hostAddress = "localhost";
    private static String multicastGroup = "230.0.0.1";
    private boolean desclassificado = false;
    private static Socket TCPsocket;
    private static DatagramSocket datagramListener;
    private static MulticastSocket multicastListener;
    private static ClientTokenAndState token = new ClientTokenAndState();

    public static void main(String[] args) {
        while (token.isAlive()) {
            try {
                TCPsocket = new Socket(hostAddress, TCPport);
                datagramListener = new DatagramSocket(UDPport);
                multicastListener = new MulticastSocket(UDPmulticastPort);
                multicastListener.joinGroup(InetAddress.getByName(multicastGroup));
                UDPThread threadUDP = new UDPThread(datagramListener);
                UDPMulticastThread threadMulticastUDP = new UDPMulticastThread(multicastListener, multicastGroup);

                TCPclientThread threadTCP = new TCPclientThread(TCPsocket, token);
                threadTCP.start();

                if (threadTCP.isAlive()) {
                    threadUDP.start();
                    threadMulticastUDP.start();
                }

                // corre enquanto a thread estiver viva
                do {
                } while (threadTCP.isAlive());

                // fechar todas as ligações
                if (threadTCP.isAlive()) {
                    threadTCP.interrupt();
                    TCPsocket.close();
                }
                if (threadUDP.isAlive()) {
                    threadUDP.interrupt();
                    datagramListener.close();
                }
                if (threadMulticastUDP.isAlive()) {
                    threadMulticastUDP.interrupt();
                    multicastListener.close();
                }

            } catch (IOException ex) {
                if (ex.getClass().isInstance(new ConnectException())) {
                    System.out.println("Erro de ligação, por favor assegure-se que está ligado à rede");
                } else {
                    ex.printStackTrace();
                }
            }
        }
    }
}
